#include "Shader.h"
#include <fstream>
#include <string>
#include <streambuf>

Shader::Shader(ShaderType type) : Resource()
{
	this->type = type;
}


Shader::~Shader(void)
{
	Dispose();
}


void Shader::LoadFromString(const char * code)
{
	this->code = code;
}

void Shader::LoadFromFile(const char * fileName)
{
	std::ifstream t(fileName);
	std::string str((std::istreambuf_iterator<char>(t)),
		std::istreambuf_iterator<char>());

	this->code = str;
}

bool Shader::Compile()
{
	if(IsAllocated() == false)
	{
		if(type == VERTEX)
			shader = glCreateShader(GL_VERTEX_SHADER);
		else shader = glCreateShader(GL_FRAGMENT_SHADER);
		const char * val = code.c_str();
		glShaderSource(shader,1,&val,nullptr);
		glCompileShader(shader);
		int lenght;
		glGetShaderiv(shader,GL_INFO_LOG_LENGTH, &lenght);

		char * log = new char[lenght];
		glGetShaderInfoLog(shader,lenght,nullptr,log);

		SetAllocated();
	}

	return true;
}

bool Shader::Compile(const char * preProccesDefinitions)
{
	if(IsAllocated() == false)
	{
		if(type == VERTEX)
			shader = glCreateShader(GL_VERTEX_SHADER);
		else shader = glCreateShader(GL_FRAGMENT_SHADER);

		const char * inputArr[2];
		inputArr[1] = code.c_str();
		inputArr[0] = preProccesDefinitions;
		glShaderSource(shader,2,inputArr,nullptr);
		glCompileShader(shader);


		int lenght;
		glGetShaderiv(shader,GL_INFO_LOG_LENGTH, &lenght);

		char * log = new char[lenght];
		glGetShaderInfoLog(shader,lenght,nullptr,log);

		SetAllocated();
	}

	return true;
}


GLuint Shader::GetGLShader()
{
	return shader;
}

void Shader::Dispose()
{

	glDeleteShader(shader);
}